package com.jokerpan.project.service.impl;

import com.jokerpan.project.entity.Chat;
import com.jokerpan.project.mapper.ChatMapper;
import com.jokerpan.project.service.ChatService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jokerpan
 */
@Service("chatService")
public class ChatServiceImpl implements ChatService {

    @Resource
    ChatMapper chatMapper;

    @Override
    public List<LinkedHashMap<String, Object>> queryChat(Chat chat) {
        List<LinkedHashMap<String, Object>> objList = chatMapper.queryChat(chat);
        Integer sendId = chat.getSendId(), receiveId = chat.getReceiveId();
        chat.setSendId(receiveId);
        chat.setReceiveId(sendId);
        List<LinkedHashMap<String, Object>> userList = chatMapper.queryChat(chat);
        List<LinkedHashMap<String, Object>> newList = new ArrayList<>();
        objList.forEach(e -> {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            LinkedHashMap<String, Object> userInfo = new LinkedHashMap<>();
            userInfo.put("avatar", e.get("sendAvatar"));
            userInfo.put("name", e.get("sendName"));
            userInfo.put("userId", e.get("sendId"));
            map.put("timestamp", Long.valueOf(e.get("time").toString()));
            map.put("userInfo", userInfo);
            map.put("value", e.get("content"));
            newList.add(map);
        });
        userList.forEach(e -> {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            LinkedHashMap<String, Object> userInfo = new LinkedHashMap<>();
            userInfo.put("avatar", e.get("sendAvatar"));
            userInfo.put("name", e.get("sendName"));
            userInfo.put("userId", e.get("sendId"));
            map.put("timestamp", Long.valueOf(e.get("time").toString()));
            map.put("userInfo", userInfo);
            map.put("value", e.get("content"));
            newList.add(map);
        });
        List<LinkedHashMap<String, Object>> list = newList.stream().sorted(Comparator.comparing(v -> v.get("timestamp").toString())).collect(Collectors.toList());
        return list;
    }

    @Override
    public boolean add(Chat chat) {
        return chatMapper.add(chat) > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        return chatMapper.deleteById(id) > 0;
    }
}
